package com.newbee.job;

import com.newbee.cache.TraceNodeCache;
import com.newbee.model.TraceNode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 链路节点批量写入任务：定时从Map缓存中获取节点，批量写入Mongo
 */
@Component
@Slf4j
public class TraceBatchWriteJob {

    @Autowired
    private TraceNodeCache traceNodeCache;

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 定时任务：每${trace.batch.write.interval}毫秒执行一次
     */
    @Scheduled(fixedRateString = "${trace.batch.write.interval:5000}")
    public void batchWriteToMongo() {
        log.info("============== batchWriteToMongo ==============");
        // 1. 从缓存批量获取节点
        List<TraceNode> nodes = traceNodeCache.batchGetAndRemove();
        if (nodes.isEmpty()) {
            return;
        }

        // 2. 批量写入Mongo
        try {
            mongoTemplate.insertAll(nodes);
            log.info("批量写入Mongo成功，节点数：{}", nodes.size());
        } catch (Exception e) {
            log.error("批量写入Mongo失败，节点数：{}", nodes.size(), e);
            // 失败时可将节点重新放回缓存（避免数据丢失）
            nodes.forEach(traceNodeCache::addNode);
        }
    }
}
